<?php

/**
 * Viewer Class
 * @author ReGeDa
 */
class Viewer extends Plugin_Object {

	/**
	 * Output type
	 * @var string
	 */
	public $type = 'plain';

	/**
	 * XSLT path
	 * @var string
	 */
	private $xslt_path;

	/**
	 * XML validation flag
	 * @var boolean
	 */
	private $xslt_validate;

	/**
	 * Content type header for XSLT
	 * @var string
	 */
	private $xslt_content_type;

	/**
	 * Get persistant plugin state
	 * @override
	 * @return boolean
	 */
	public function is_persistant() {
		return TRUE;
	}

	/**
	 * Output a string
	 * @param string $str
	 */
	private function flush($str, $content_type) {

		if ( ! is_null($content_type))
			platcode()->plugins->import('HTTP')->set_header('Content-Type',$content_type);

		echo $str;

		platcode()->terminate();
	}

	/**
	 * Casting XML data in Platcode RAW
	 * @return XML
	 */
	private function &casting_xml() {

		$xml = platcode()->raw;

		// convert array to XML
		if (is_array($xml))
			return platcode()->plugins->import('XML')->serialize($xml);
		// check XML data type
		else if ($xml instanceof XML)
			return $xml;
		// error
		else
			throw new Platcode_Exception('No XML data in RAW variable');
	}

	/**
	 * Global response
	 */
	public function response() {
		if (method_exists($this, $this->type))
			call_user_func(array($this, $this->type));
		else
			throw new Platcode_Exception("Unknown Viewer '$this->type' type");
	}

	/**
	 * Prepare XSLT parameters
	 * @param string $path
	 * @param boolean $validate
	 * @param string $content_type
	 */
	public function prepare_xslt($path, $validate = FALSE, $content_type = NULL) {
		$this->type = 'xslt';
		$this->xslt_path = $path;
		$this->xslt_validate = $validate;
		$this->xslt_content_type = $content_type;
	}

	/**
	 * Output XML document
	 */
	protected function xslt() {
		$this->flush(
			$this->casting_xml()->transform($this->xslt_path, $this->xslt_validate),
			$this->xslt_content_type
		);
	}

	/**
	 * Output XML string
	 */
	protected function xml() {
		$this->flush(
			$this->casting_xml()->DOM->saveXML(),
			'text/xml'
		);
	}

	/**
	 * Output JSON string
	 */
	protected function json() {
		$this->flush(
			json_encode(platcode()->raw),
			'application/json'
		);
	}

	/**
	 * Output PLAIN text
	 */
	protected function plain() {
		$this->flush(
			print_r(platcode()->raw, TRUE),
			'text/plain'
		);
	}

	/**
	 * Output JavaScript callback
	 */
	protected function jcallback() {

		// callback handler
		$callback = platcode()->plugins->import('Input')->post('callback');

		if ( ! $callback)
			$callback = 'alert';

		// output
		$this->flush(
			"<script type=\"text/javascript\">\nwindow.top.window.$callback(".json_encode(platcode()->raw).");\n</script>",
			'text/html'
		);
	}
}

// end of file